package com.today.usercenter.ui.activities;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qmuiteam.qmui.widget.QMUITopBar;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.today.lib.common.ui.base.RxBaseActivity;
import com.today.lib.common.utils.ToastUtils;
import com.today.usercenter.R;
import com.today.usercenter.R2;
import com.today.usercenter.TaskManager;
import com.today.usercenter.network.entity.TaskInfoEntity;
import com.today.usercenter.ui.adapters.TaskListAdapter;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TaskCenterActivity extends RxBaseActivity {
    @BindView(R2.id.topbar)
    QMUITopBar mTopBar;
    @BindView(R2.id.task_list)
    RecyclerView mTaskList;

    @OnClick({R2.id.show_rule})
    public void onShowRule(View view) {
        TaskManager.getInstance().showRulePage(this);
    }

    private QMUITipDialog tipDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_task_center;
    }

    @Override
    public void init(Bundle savedInstanceState) {

        initTopBar();

        List<TaskInfoEntity.DataBean> tasks = TaskManager.getInstance().getAll();
        if (tasks == null) {
            if (tipDialog == null)
                tipDialog = new QMUITipDialog.Builder(this)
                        .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                        .setTipWord("任务加载中...")
                        .create();

            tipDialog.show();

            TaskManager.getInstance().load((success) -> {
                if (success) {
                    initTasksList(TaskManager.getInstance().getAll());
                } else {
                    ToastUtils.showToast("加载任务失败");
                }
                if (tipDialog != null) {
                    tipDialog.dismiss();
                    tipDialog = null;
                }
            });
        } else {
            initTasksList(tasks);
        }
    }

    public void initTasksList(List<TaskInfoEntity.DataBean> tasks) {
        TaskListAdapter adapter = new TaskListAdapter(tasks, this);
        mTaskList.setLayoutManager(new LinearLayoutManager(this));
        mTaskList.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mTaskList.setAdapter(adapter);
    }

    public void onTaskItemClick(View view){
        ToastUtils.showToast("任务自动记录中...");

        finish();
    }


    private void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.colorPrimary));
        mTopBar.addLeftBackImageButton().setOnClickListener(v -> finish());

        mTopBar.setTitle(R.string.task_center);
    }
}
